<?php
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 路人甲乙科技有限公司 [ http://www.lurenjiayi.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://lurenjiayi.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author menghui
// +----------------------------------------------------------------------
namespace app\statistics\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

use app\stock\model\Borrow;
use think\Db;
use think\Config;
class Agent extends Admin{
    //模拟盘统计
    public function index(){

        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 获取查询条件
        $map = $this->getMap();
        $order = $this->getOrder();
//        $data_list = MemberModel::getAgentList($map,$order);
        $data_list = Db::name('member')
            ->where($map)
            ->where('agent_id<>0')
            ->order($order)
            ->paginate()
            ->each(function($item, $key){
                $info = get_agents_info($item['agent_far']);
                $item['agent_far_name'] = $info['mobile'] ?  $info['mobile'] : config('web_site_title');
                $count = Db::name('agents_back_money')->where(['mid'=>$item['id']])->sum('affect');
                $item['count_profit'] = round($count,2);
                $item['agent_back_rate'] = get_plus_rate($item['id']).'%';
                return $item;
            });
        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
            ->setTableName('member')
            ->setSearch(['mobile' => '代理商手机号', 'agent_far_name'=>'所属代理','agent_id'=>'代理商等级'],'','',true) // 设置搜索框
            ->addOrder('create_time,id desc') // 添加排序
            ->hideCheckbox()
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['mobile', '代理商手机号'],
                ['name', '代理商姓名'],
                ['agent_id','代理等级', 'text','',[0=>'普通会员',1=>'一级代理',2=>'二级代理',3=>'三级代理']],
                ['agent_far_name', '上级代理'],
                ['agent_back_rate', '上级返佣比例'],
                ['count_profit', '佣金总收益'],
                ['agent_pro', '代理状态', [0=>'停止', 1=>'正常']],
                ['create_time', '注册时间', 'datetime'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
	
	
	//佣金明细
    public function detail(){
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
        // 获取查询条件
		$agentWhere = [];
		$keyword = trim(input('param.keyword/s', ''));
		if($keyword<>""){
			$agent = Db::name("member")->where('mobile', $keyword)->where('agent_id<>0')->find();
			if($agent['id']>0){
				$agentWhere['agent_far'] = $agent['id'];
			}else{
				$agentWhere['mobile'] = $keyword;
			}
		}
		
		$map = $this->getMap();
		if(empty($map['detail_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['detail_date'][1][0]));
        }
        if(empty($map['detail_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['detail_date'][1][1]));
        }
		unset($map['detail_date']);
		
		
        // 排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='b.create_time desc';
        }
		
		$GLOBALS['detail_costs'] = 0;
		$GLOBALS['detail_delays'] = 0;
		$GLOBALS['detail_buys'] = 0;
		$GLOBALS['detail_sells'] = 0;
		$GLOBALS['detail_earns'] = 0;
		$GLOBALS['detail_beginday'] = $beginday;
		$GLOBALS['detail_endday'] = $endday;
		
        // 数据列表		
        $data_list = Db::view('stock_borrow b')
            ->view("member", 'mobile as business_mobile,name,agent_far', 'member.id=b.member_id', 'left')
            ->view("stock_subaccount s",'sub_account','s.id=b.stock_subaccount_id','left')
            ->where($agentWhere)
            ->where('b.status=2')
			->where("b.end_time > " . strtotime($GLOBALS['detail_beginday']." 00:00:00"))
			->where("b.end_time < " . strtotime($GLOBALS['detail_endday']." 23:59:59"))
            ->order($order)
            ->paginate()
            ->each( function($item, $key){
                $item['deposit_money'] = money_convert($item['deposit_money']);
                $item['init_money'] = money_convert($item['init_money']);
                $item['borrow_money'] = money_convert($item['borrow_money']);
                $item['borrow_interest'] = money_convert($item['borrow_interest']);
                $item['stock_money'] = money_convert($item['stock_money']);
				$item['type'] = (int)$item['type'];
				if($item['type']===3){$unit='个月';}elseif($item['type']===2){$unit='周';}else{$unit='天';}
                $item['borrow_duration'] .= $unit;
				
				
				$agent = get_agents_info($item['agent_far']);
                $item['agent_mobile'] = $agent['mobile'] ?  $agent['mobile'] : config('web_site_title');
				
				
                $item['cost'] = money_convert($item['deposit_money'] * $item['rate'] * $item['borrow_duration']  * 10);                
				$delay = ceil(($item['end_time'] - $item['verify_time']) / 86400) - $item['borrow_duration'];
				$item['delay'] = money_convert($item['deposit_money'] * $item['rate'] * $delay  * 10);				
				
				
				$item['cost'] = $item['borrow_interest']; 
				$item['delay'] = 0;						
				$item['buy'] = Db::name('stock_delivery_order')->where(['sub_id'=>$item['stock_subaccount_id'],'business_name'=>'证券买入'])->sum('liquidation_amount-residual_quantity');
				$item['sell'] = Db::name('stock_delivery_order')->where(['sub_id'=>$item['stock_subaccount_id'],'business_name'=>'证券卖出'])->sum('residual_quantity-liquidation_amount');
                $item['earn'] = round($item['stock_money']-$item['init_money'], 2);
				
				$GLOBALS['detail_costs'] = $GLOBALS['detail_costs'] + $item['cost'];
				$GLOBALS['detail_delays'] = $GLOBALS['detail_delays'] + $item['delay'];
				$GLOBALS['detail_buys'] = $GLOBALS['detail_buys'] + $item['buy'];
				$GLOBALS['detail_sells'] = $GLOBALS['detail_sells'] + $item['sell'];
				$GLOBALS['detail_earns'] = $GLOBALS['detail_earns'] + $item['earn'];
				
				return $item;
            });
		
        // 分页数据
        $page = $data_list->render();
		$html .= "<p style='padding-left:10px'>";
		$html .= "配置管理费："	.$GLOBALS['detail_costs']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "延期费："		.$GLOBALS['detail_delays']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "买入手续费："	.$GLOBALS['detail_buys']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "卖出手续费："	.$GLOBALS['detail_sells']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "盈亏："		.$GLOBALS['detail_earns']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "</p>";

		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')		
            ->setTableName('stock_borrow')
			->addTimeFilter('detail_date', [$beginday, $endday])
            ->setSearch(['agent_mobile' => '代理商手机号', 'business_mobile' => '商户手机号'],'','',true)
            ->addOrder('order_id,name,create_time') // 添加排序
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['order_id', '订单号'],
                ['business_mobile', '商户手机号'],
                ['agent_mobile', '代理商手机号'],
                ['cost','配资管理费（元）'],
				['delay', '延期费（元）'],
                ['buy','买入手续费（元）'],
                ['sell','卖出手续费（元）'],
                ['earn','盈亏（元）'],
				['verify_time','开始时间','datetime'],
				['end_time','终止时间','datetime'],
                //['right_button', '操作', 'btn']
            ])
			// 设置表格数据
            ->setRowList($data_list) 
			// 设置分页数据
			->setPages($page) 
			// 设置底部总计
			->setExtraHtml($html, 'table_bottom')
			// 渲染模板
            ->fetch(); 
    }
	
	//汇总查询
    public function gather(){
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
        // 获取查询条件
        $map = $this->getMap();
		if(empty($map['gather_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['gather_date'][1][0]));
        }
        if(empty($map['gather_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['gather_date'][1][1]));
        }
		unset($map['gather_date']);
        $order = $this->getOrder();
		
		$GLOBALS['gather_recharges'] = 0;
		$GLOBALS['gather_withdraws'] = 0;
		$GLOBALS['gather_profits'] = 0;
		$GLOBALS['gather_beginday'] = $beginday;
		$GLOBALS['gather_endday'] = $endday;
		
        $data_list = Db::name('member')
            ->where($map)
            ->where('agent_id<>0')
            ->order($order)
            ->paginate()
            ->each(function($item, $key){
                $agent = get_agents_info($item['agent_far']);
                $item['agent_far_name'] = $agent['mobile'] ?  $agent['mobile'] : config('web_site_title');
                
				
				$members = Db::name('member')->where(['agent_far'=>$item['id']])->field('id')->select();
				$members = array_column($members, 'id');
				
				
				$count = Db::name('money_recharge')
							->where('mid','in',$members)
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->where('status=1')
							->sum('money');
				$item['count_recharge'] = money_convert($count);
				
				
				$count = Db::name('money_withdraw')
							->where('mid','in',$members)
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->where('status=1')
							->sum('money');
				$item['count_withdraw'] = money_convert($count);
				
				
				$count = Db::name('agents_back_money')
							->where(['mid'=>$item['id']])
							->where("create_time > " . strtotime($GLOBALS['gather_beginday']." 00:00:00"))
							->where("create_time < " . strtotime($GLOBALS['gather_endday']." 23:59:59"))
							->sum('affect');
                $item['count_profit'] = round($count,2);
				
				
				
				$GLOBALS['gather_recharges'] = $GLOBALS['gather_recharges'] + $item['count_recharge'];
				$GLOBALS['gather_withdraws'] = $GLOBALS['gather_withdraws'] + $item['count_withdraw'];
				$GLOBALS['gather_profits'] = $GLOBALS['gather_profits'] + $item['count_profit'];
                return $item;
            });
		
        // 分页数据
        $page = $data_list->render();
		$html .= "<p style='padding-left:10px'>";
		$html .= "充值总金额："	.$GLOBALS['gather_recharges']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "提现总金额："	.$GLOBALS['gather_withdraws']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		//$html .= "佣金总金额："	.$GLOBALS['gather_profits']." 元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$html .= "</p>";
		
		
        return ZBuilder::make('table')
            ->setTableName('member')
			->addTimeFilter('gather_date', [$beginday, $endday])
            ->setSearch(['mobile' => '代理商手机号'],'','',true)
            ->hideCheckbox()
            ->addColumns([
                ['id', 'ID'],
                ['mobile', '代理商手机号'],
                ['name', '代理商姓名'],
                ['count_recharge', '充值金额（元）'],
                ['count_withdraw', '提现金额（元）'],
                //['count_profit', '佣金金额（元）'],
            ])
			
			// 设置表格数据
            ->setRowList($data_list) 
			
			// 设置底部总计
			->setExtraHtml($html, 'table_bottom')
			
			// 渲染模板
            ->fetch(); 
    }
	
    /*
     * 实盘用户统计
     */
    public function agent_stock(){


        $map = $this->getMap();
        // 获取排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='d.id desc';
        }
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:20;
        if(empty($map['deal_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['deal_date'][1][0]));
        }
        if(empty($map['deal_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['deal_date'][1][1]));
        }
        $data_list = Db::view('stock_deal_stock d')
            ->view('stock_subaccount s','sub_account','s.id=d.sub_id','left')
            ->view('stock_borrow b','deposit_money,borrow_money','b.stock_subaccount_id=s.id','left')
            ->view('member m','name,mobile,agent_far','m.id=b.member_id','left')
            ->where('d.status','<>','0')
            ->where($map)
            ->where("d.soruce !='模拟账户'")
            ->order($order)
            ->paginate($listRows)
            ->each(function($item, $key){
                $info = get_agents_info($item['agent_far']);
                $item['agent_far_name'] = $info['mobile'] ?  $info['mobile'] : config('web_site_title');
                return $item;
            });

        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
            ->setPageTitle('历史成交') // 设置页面标题
            ->addTopButton('custem',$btn_excel)
            ->setTableName('stock_deal_stock') // 设置数据表名
            ->addTimeFilter('deal_date', [$beginday, $endday]) // 添加时间段筛选
            ->addOrder('sub_id,gupiao_code,gupiao_name') // 添加排序
            ->addFilter('gupiao_code,soruce') // 添加筛选
            ->setSearch([ 'mobile' => '手机号','agent_far_name' => '所属代理商']) // 设置搜索参数
            ->addRightButton('edit') // 添加编辑按钮
            ->addColumns([ // 批量添加列
                ['sub_id', '子账户ID'],
                ['mobile', '手机号'],
                ['name', '所属代理商'],
                ['agent_far_name', '所属代理商'],
                ['sub_account', '子账户名称'],
                ['deposit_money', '保证金'],
                ['borrow_money', '配资金额'],
                ['gupiao_name', '证券名称'],
                ['trust_price', '成本均价'],
                ['gupiao_code', '证券代码'],
                ['deal_price', '平仓价'],
                ['amount', '成交金额'],
                ['volume', '卖出数量'],
                ['deal_date', '卖出时间','date'],
            ])
            ->hideCheckbox()
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();

    }
    /*
    * 实盘用户统计
    */
    public function agent_count(){

        $map = $this->getMap();
        // 获取排序
        $order = $this->getOrder();
        if(empty($order)){
            $order='d.id desc';
        }
        $list_rows1 = input('list_rows');
        $listRows = isset($list_rows1)?$list_rows1:20;
        if(empty($map['deal_date'][1][0])){
            $beginday=date('Ymd',time()-2592000);//30天前
        }else{
            $beginday=date('Ymd',strtotime($map['deal_date'][1][0]));
        }
        if(empty($map['deal_date'][1][1])){
            $endday=date('Ymd',time());
        }else{
            $endday=date('Ymd',strtotime($map['deal_date'][1][1]));
        }
        $data_list = Db::view('stock_deal_stock d')
            ->view('stock_subaccount s','sub_account','s.id=d.sub_id','left')
            ->view('stock_borrow b','deposit_money,borrow_money','b.stock_subaccount_id=s.id','left')
            ->view('member m','name,mobile,agent_far','m.id=b.member_id','left')
            ->where('d.status','<>','0')
            ->where($map)
            ->where("d.soruce ='模拟账户'")
            ->order($order)
            ->paginate($listRows)
            ->each(function($item, $key){
                $info = get_agents_info($item['agent_far']);
                $item['agent_far_name'] = $info['mobile'] ?  $info['mobile'] : config('web_site_title');
                return $item;
            });

        if(empty($_SERVER["QUERY_STRING"])){
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"],0,-5)."_export";
        }else{
            $excel_url=substr(http().$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"],0,-5)."_export?".$_SERVER["QUERY_STRING"];
        }
        $btn_excel = [
            'title' => '导出EXCEL表',
            'icon'  => 'fa fa-fw fa-download',
            'href'  => url($excel_url,'','')
        ];
        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
            ->setPageTitle('历史成交') // 设置页面标题
            ->addTopButton('custem',$btn_excel)
            ->setTableName('stock_deal_stock') // 设置数据表名
            ->addTimeFilter('deal_date', [$beginday, $endday]) // 添加时间段筛选
            ->addOrder('sub_id,gupiao_code,gupiao_name') // 添加排序
            ->addFilter('gupiao_code,soruce') // 添加筛选
            ->setSearch([ 'mobile' => '手机号','agent_far_name' => '所属代理商']) // 设置搜索参数
            ->addRightButton('edit') // 添加编辑按钮
            ->addColumns([ // 批量添加列
                ['sub_id', '子账户ID'],
                ['mobile', '手机号'],
                ['name', '所属代理商'],
                ['agent_far_name', '所属代理商'],
                ['sub_account', '子账户名称'],
                ['deposit_money', '保证金'],
                ['borrow_money', '配资金额'],
                ['gupiao_name', '证券名称'],
                ['trust_price', '成本均价'],
                ['gupiao_code', '证券代码'],
                ['deal_price', '平仓价'],
                ['amount', '成交金额'],
                ['volume', '卖出数量'],
                ['deal_date', '卖出时间','date'],
            ])
            ->hideCheckbox()
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();

    }
}